/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.models.analyze;

import app.Const;
import app.kit.TypeKit;
import app.models.member.Member;
import app.models.product.Product;
import com.google.common.primitives.Doubles;
import com.jfinal.plugin.activerecord.Model;
import goja.StringPool;
import goja.annotation.TableBind;
import goja.plugins.sqlinxml.SqlKit;
import org.joda.time.DateTime;

import java.util.List;

/**
 * <p>
 * The table rlp_track_record mapping model.
 * </p>
 */
@TableBind(tableName = "rla_product_record")
public class ProductRecord extends Model<ProductRecord> {

    /**
     * The public dao.
     */
    public static final ProductRecord dao = new ProductRecord();

    private static final long serialVersionUID = -4547122046791891036L;


    /**
     * 纪录投资纪录
     *
     * @param product 产品
     * @param member  会员
     * @param amount  投资金额
     * @param now     购买时间
     */
    public void record(Product product, Member member, Double amount, DateTime now) {
        ProductRecord record = new ProductRecord();
        record.set(Const.FIELD_PRODUCT, product.getInt(StringPool.PK_COLUMN));
        record.set("investor", member.getInt(StringPool.PK_COLUMN));
        record.set("investor_disaplay", member.getStr(Const.FIELD_NAME));
        record.set("investor_amount", amount);
        record.set("investor_date", now.toDate());
        record.set("investor_datetime", now.toDate());
        DateTime valuedate = now.plusDays(product.getInt("valuedate_offset"));
        record.set("valuedate", valuedate.toDate());
        record.save();
    }

    /**
     * 通过产品查询购买记录
     * @param product 产品id
     */
    public long findByCountBuys(int product) {
        final ProductRecord productRecord = ProductRecord.dao.find(SqlKit.sql("productreocrd.findByCountBuys"), product).get(0);
        return TypeKit.getLong(productRecord, "c");
    }

    /**
     *
     */
    public int getCountAll(){
        return TypeKit.getInt(findFirst(SqlKit.sql("productreocrd.getCountAll")), "cnt");
    }

    public Double getSumAmount() {
        return TypeKit.getDouble(findFirst(SqlKit.sql("productreocrd.getSumAmount")),"amount_sum");
    }

    public int getPersonCount() {
        return TypeKit.getInt(findFirst(SqlKit.sql("productreocrd.getPersonCount")), "peson_cnt");
    }

    public List<ProductRecord> dealAmountChat() {
        List<ProductRecord> productRecords = find(SqlKit.sql("productreocrd.dealAmountChat"));
        return productRecords;
    }
}